#include "MorphologyEx.h"
#include "../utils/Logger.h"

MorphologyEx::MorphologyEx(int operation, int iterations, int aperture) :
        operation(operation),
        iterations(iterations),
        kernel(cvCreateStructuringElementEx(aperture, aperture, aperture >> 1, aperture >> 1, CV_SHAPE_RECT))
{
}

MorphologyEx::~MorphologyEx() {
    cvReleaseStructuringElement(&kernel);
}

IplImage* MorphologyEx::apply(const IplImage* in) {
    Log << "Applying morphologyEx effect: " <<
            kernel->nCols << ", " <<
            operation << ", " <<
            iterations << endl;

    IplImage *out = cvCreateImage(cvSize(in->width, in->height), in->depth, in->nChannels);

    IplImage *tmp = NULL;
    if (CV_MOP_GRADIENT == operation)
        tmp = cvCreateImage(cvSize(in->width, in->height), in->depth, in->nChannels);
    
    cvMorphologyEx(in, out, tmp, kernel, operation, iterations);

    if (tmp)
        cvReleaseImage(&tmp);

    return out;
}
